package com.hn658.base.message.eventbus.handler;

import com.hn658.base.message.eventbus.event.Event;
import com.hn658.base.message.eventbus.exception.EventbusException;
import com.hn658.framework.common.AbstractBusinessObject;
import com.hn658.framework.logging.enums.LogCategory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by baihai on 2015/11/19.
 */
@Component
public class EventDealManagerImpl extends AbstractBusinessObject
        implements InitializingBean, ApplicationContextAware,IEventDealManager {


    private Map<Integer, IEventHandler> eventHandlerMap;
    private ApplicationContext context;


    @Override
    public void handleEvent(Event event) {

          if(event == null){
                throw new EventbusException(EventbusException.EmptyEventError);
          }

          if(event.getType()==null){

                throw new EventbusException(EventbusException.EmptyEventTypeError);
          }

         IEventHandler handler = eventHandlerMap.get(event.getType().getValue());

         if(handler == null){

                throw new EventbusException(EventbusException.EmptyHandlerError);
         }

         handler.handle(event);


    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
        eventHandlerMap = new HashMap<Integer, IEventHandler>();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initOrderStatusHandler();
    }


    private void initOrderStatusHandler() {

        Map<String, IEventHandler> beans = context
                .getBeansOfType(IEventHandler.class);
        if (beans != null && beans.size() > 0) {
            logger.info(LogCategory.SYSTEM,
                    String.format("共找到%s个IEventHandler事件相关的处理类", beans.size()));

            for (Map.Entry<String, IEventHandler> entry : beans
                    .entrySet()) {
                IEventHandler handler = entry.getValue();

                if (handler.getTarget() == null) {
                    logger.error(LogCategory.ORDER, String.format(
                            "%s实现类方法getTarget方法不能返回空，必须返回有效值",
                            handler.getClass()));
                } else {
                    eventHandlerMap.put(
                            Integer.valueOf(handler.getTarget().getValue()),
                            handler);
                }
            }
        } else {
            logger.info(LogCategory.ORDER,
                    String.format("没有找到相关的事件处理接口(IEventHandler)实现类"));
        }

    }


}
